import pygame,sys,os,eztext,Frontier
from pygame.locals import *

boardSizeX = 630
boardSizeY = 630
boardSpacesX = 9
boardSpacesY = 9
bufferX = 45
bufferY = 45
screenSizeX = 1280
screenSizeY = 720

def screenSetup():
    '''setup the background and prepare the screen for use'''
    global backgroundSurface
    global screen
    backgroundFileName = os.path.join("data","menuBackground.png") 
    backgroundSurface = pygame.image.load(backgroundFileName)
    screen.blit(backgroundSurface,(0,0))
    pygame.display.flip()
    
def menuSpotSetup():
    global menuSpotSprites
    menuSpotSprites = pygame.sprite.Group()
    xOrig = 800
    yOrig = 50
    step = 80
    x = xOrig
    y = yOrig
    menuSpotSprites.add(Frontier.Ground(x,y))
    x += step
    menuSpotSprites.add(Frontier.Forest(x,y))
    x += step
    menuSpotSprites.add(Frontier.MagicForest(x,y))
    x += step
    menuSpotSprites.add(Frontier.GoldMine(x,y))
    x = xOrig
    y += step
    menuSpotSprites.add(Frontier.Mountain(x,y))
    x += step
    menuSpotSprites.add(Frontier.Water(x,y))
    x += step
    menuSpotSprites.add(Frontier.Lava(x,y))
    
def load_image(name,colorkey):
    '''load an image from the data folder'''
    fullname = os.path.join("data", name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print "Cannot load image:", name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)

    return image
    
def selectSpot(spot):
    global selected
    unselect()
    selected = spot
    #showMenu()
    SpotHighlight(spot.rect.center)
    
def unselect():
    statSprites.clear(screen,backgroundSurface)
    statSprites.empty()
    inputSprites.clear(screen,backgroundSurface)
    inputSprites.empty()
    
def buttonSetup():
    '''make the save/reset/exit buttons'''
    ResetButton()
    SaveButton()
    ExitButton()
    
def saveMap(name):
    fileName = os.path.join("maps",name+".map")
    f = open(fileName,'w')
    boardSpots = 81
    spaceX = boardSizeX/boardSpacesX
    spaceY = boardSizeY/boardSpacesY
    x = bufferX
    y = bufferY
    mapList = []
    for a in range(boardSpots):
        for spot in spotSprites:
            if spot.rect.topleft == (x,y):
                mapList.append(spot.name+"\n")
                if x < (bufferX + boardSizeX - spaceX):
                    x += spaceX
                else:
                    x = bufferX
                    y += spaceY
                break
    for a in mapList:
        fileLine = a
        f.write(fileLine)
    f.write("end")
    f.close()
    
def switchSpot(spot):
    global spotSprites
    spotName = selected.name
    x,y = spot.rect.topleft
    sprite = None
    if spotName == "Field":
        sprite = Frontier.Ground(x,y)
    elif spotName == "Mountain":
        sprite = Frontier.Mountain(x,y)
    elif spotName == "Water":
        sprite = Frontier.Water(x,y)
    elif spotName == "Lava":
        sprite = Frontier.Lava(x,y)
    elif spotName == "Magic Forest":
        sprite = Frontier.MagicForest(x,y)
    elif spotName == "Gold Mine":
        sprite = Frontier.GoldMine(x,y)
    elif spotName == "Forest":
        sprite = Frontier.Forest(x,y)
    if sprite != None:
        spotSprites.add(sprite)
        spot.kill()
        

def run(theScreen):
    '''essentially the main() function for MapEditor'''
    #get the screen from the main program
    global screen
    global statSprites
    global spotSprites
    global inputSprites
    global messageSprites
    global buttonSprites
    global selected
    global end
    selected = None
    screen = theScreen
    
    screenSetup()
    
    menuSpotSetup()
    spotSprites = Frontier.boardSetup("field.map")
    statSprites = pygame.sprite.Group()
    inputSprites = pygame.sprite.Group()
    messageSprites = pygame.sprite.Group()
    buttonSprites = pygame.sprite.Group()
    buttonSetup()
    
    end = False
    clock = pygame.time.Clock()
    while end == False:
        clock.tick(60)
        events = pygame.event.get()
        for event in events:
             
            if event.type == QUIT:
                
                sys.exit(0)
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                if menuSpotSprites.has(selected):
                    for spot in spotSprites:
                        if spot.rect.collidepoint(pos):
                            switchSpot(spot)
                for spot in menuSpotSprites:
                    if spot.rect.collidepoint(pos):
                        selectSpot(spot)
                for button in buttonSprites:
                    if button.rect.collidepoint(pos):
                        button.function() 
        buttonSprites.update(events)
        messageSprites.update()                
        
        spotSprites.draw(screen)
        menuSpotSprites.draw(screen)
        buttonSprites.draw(screen)
        statSprites.draw(screen)
        
        messageSprites.draw(screen)
        pygame.display.flip()
    screen.blit(backgroundSurface,(0,0))
class Stats(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.font = pygame.font.Font(None,24)
        self.color = (0,0,0)
        statSprites.add(self)
class SpotHighlight(Stats):
    def __init__(self,center):
        Stats.__init__(self)
        self.image = load_image("spotSelected.png",-1)
        self.rect = self.image.get_rect()
        self.rect.center = center
        
class Buttons(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        buttonSprites.add(self)
        self.selected = False
class ResetButton(Buttons):
    def __init__(self):
        Buttons.__init__(self)
        self.image = load_image("resetButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (700,620)
    def function(self):
        global spotSprites
        spotSprites.clear(screen,backgroundSurface)
        spotSprites.empty()
        spotSprites = Frontier.boardSetup("field.map")
class SaveButton(Buttons):
    def __init__(self):
        Buttons.__init__(self)
        self.image = load_image("saveButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (850,620)
    def function(self):
        global selected
        unselect()
        txtLocX = self.rect.topleft[0]
        txtLocY = self.rect.topleft[1] -20
        txtbox = eztext.Input(x=txtLocX,y=txtLocY,color=(0,0,0),prompt=("What shall we name it?: "))
        inputSprites.add(txtbox)
        inputSprites.draw(screen)
        self.selected = True
    def update(self,events):
        if self.selected == True:
            for event in events:
                if event.type == KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        for sprite in inputSprites:
                            name = sprite.value
                        try:
                            saveMap(name)
                            inputSprites.empty()
                            Error("Saved Successfully as " + name+ ".map!")
                        except:
                            Error("Not a valid file name (.deck suffix automatically added)")
            global screen
            global backgroundSurface
            inputSprites.update(events)
            inputSprites.clear(screen,backgroundSurface)
            inputSprites.draw(screen)
    def unselect(self):
        global selected
        self.selected = False
class ExitButton(Buttons):
    def __init__(self):
        Buttons.__init__(self)
        self.image = load_image("exitButton.png",-1)
        self.rect = self.image.get_rect()
        self.rect.topleft = (1000,620)
    def function(self):
        global end
        end = True
        
class Error(pygame.sprite.Sprite):
    def __init__(self,text):
        pygame.sprite.Sprite.__init__(self)
        color = (250,0,0)
        self.font = pygame.font.Font(None,30)
        self.surface =self.font.render(text,1,color)
        self.image = self.surface
        self.rect = self.surface.get_rect()
        self.rect.center = (1280/2,250 + len(messageSprites)*30)
        messageSprites.add(self)
        self.activated = True
        self.counter = 0
    def update(self):
        if self.activated == True:
            self.counter +=1
            if self.counter >= 80:
                messageSprites.clear(screen,backgroundSurface)
                self.kill()
                del self